# coding:utf-8
"""
    Author: haojuetrace
    Time: 2023-09-17
"""
import os
import sys

from wordpress_xmlrpc import Client
import frontmatter as frontmatter

from mistune import HTMLRenderer, Markdown
from wordpress_xmlrpc.methods import taxonomies
from wordpress_xmlrpc.methods.posts import EditPost


def update_post_content(post, filepath, client):
    """
    更新文章内容
    :param post: 文章内容
    :param filepath: 要更新的文件路径
    :param client: wp客户端
    :return:
    """
    # 载入文件内容
    post_from_file = frontmatter.load(filepath)
    # print(post_from_file)
    # 2 markdown库导入内容
    md = Markdown(renderer=HTMLRenderer(escape=False))
    post_content_html = md(post_from_file.content)
    # 下面这种转换的html格式有错误所以更换了模块
    # post_content_html = markdown.markdown(post_from_file.content,
    #                                       extensions=['markdown.extensions.fenced_code']).encode("utf-8")
    # print(post_from_file.metadata)

    # 判断文章的元数据是否包含postId，如果有代表已经上传过的文件，没有则代表没上传过的文件
    if post_from_file.metadata.get("postId") is None:
        print("文章未上传过，省略")
        return False

    # 通过分割获取文件名，让其作为文章的标题
    post.title = os.path.basename(filepath).split('.md')[0]
    # print(post_from_file.metadata["postId"])
    # print(post_from_file.metadata["tags"])
    # 获取文章密码，可无
    if not post_from_file.metadata.get("post_password") is None:
        post.password = post_from_file.metadata["post_password"]
    # 发布文章时的状态
    post.post_status = 'publish'  # 文章状态，不写默认是草稿，private表示私密的，draft表示草稿，publish表示发布
    post.content = post_content_html  # 修改内容
    # 将分类id转换成分类名称
    categorys = []
    for i in range(len(post_from_file.metadata["categories"])):
        # print(post_from_file.metadata["categories"][i], i)
        categorys.append(client.call(taxonomies.GetTerm('category', post_from_file.metadata["categories"][i])).name)
    # print(categorys)
    # 格式化文章标签和分类
    post.terms_names = {
        'post_tag': post_from_file.metadata["tags"],
        'category': categorys
    }
    # 调用修改文章的函数
    return client.call(EditPost(post_from_file.metadata["postId"], post))


def wp_xmlrpc(domain, username, password):
    """
    ### Description
    The Client function with error control

    ### Parameters
    + domain: The domain of the WordPress site.
    + username: The user name of the WordPress site.
    + password: The password of the user name.

    ### Return
    A Client object
    """
    try:
        client = Client(domain + '/xmlrpc.php', username, password)  # 客户端
        print('SUCCESS to connect to your WordPress website: ' + domain)
        return client
    except Exception as e:
        print('FAILED to connect to your WordPress website: ' + str(e))
        # 正常退出
        sys.exit(0)
